# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


class Product:
    def __init__(self, product_id, name, price, stock):
        self.product_id = product_id
        self.name = name
        self.price = price
        self.stock = stock


products = []


def add_product():
    try:
        print("\n添加新商品")
        product_id = input("请输入商品ID：").strip()

        # 检查ID是否已存在
        if any(p.product_id == product_id for p in products):
            print("错误：该ID已存在！")
            return

        name = input("请输入商品名称：").strip()
        if not name:
            print("错误：商品名称不能为空！")
            return

        price = float(input("请输入商品价格："))
        stock = int(input("请输入初始库存："))

        if price < 0 or stock < 0:
            print("错误：价格和库存不能为负数！")
            return

        new_product = Product(product_id, name, price, stock)
        products.append(new_product)
        print("✅ 商品添加成功！")

    except ValueError:
        print("输入格式错误，请检查数字输入！")


def display_products():
    print("\n📋 商品列表：")
    print(f"{'ID':<6}{'名称':<10}{'价格':<8}{'库存':<6}")
    print("-" * 35)
    for p in products:
        print(f"{p.product_id:<6}{p.name:<10}{p.price:<8.2f}{p.stock:<6}")


def find_product(product_id):
    for p in products:
        if p.product_id == product_id:
            return p
    return None


def update_product():
    product_id = input("请输入要修改的商品ID：")
    product = find_product(product_id)

    if not product:
        print("错误：找不到该商品！")
        return

    print("\n当前商品信息：")
    print(f"1. 名称：{product.name}")
    print(f"2. 价格：{product.price:.2f}")

    try:
        choice = input("请选择要修改的项（1-2，多个用逗号分隔）：")
        fields = choice.split(',')

        for field in fields:
            if field.strip() == '1':
                new_name = input("请输入新名称：").strip()
                if new_name:
                    product.name = new_name
            elif field.strip() == '2':
                new_price = float(input("请输入新价格："))
                if new_price >= 0:
                    product.price = new_price
                else:
                    print("价格不能为负数，修改未生效")
        print("✅ 商品信息已更新")

    except ValueError:
        print("输入格式错误！")


def delete_product():
    product_id = input("请输入要删除的商品ID：")
    product = find_product(product_id)

    if product:
        products.remove(product)
        print("✅ 商品已删除")
    else:
        print("错误：找不到该商品！")


def adjust_stock():
    product_id = input("请输入要调整库存的商品ID：")
    product = find_product(product_id)

    if not product:
        print("错误：找不到该商品！")
        return

    try:
        print(f"当前库存：{product.stock}")
        operation = input("请选择操作（1.增加 2.减少）：")
        amount = int(input("请输入调整数量："))

        if operation == '1':
            product.stock += amount
        elif operation == '2':
            if amount > product.stock:
                print("警告：库存不足，将清空库存")
                product.stock = 0
            else:
                product.stock -= amount
        else:
            print("无效的操作类型")
            return

        print(f"✅ 库存已更新，当前库存：{product.stock}")

    except ValueError:
        print("请输入有效的数字！")


def show_menu():
    while True:
        print("\n=== 商品管理系统 ===")
        print("1. 添加商品")
        print("2. 显示所有商品")
        print("3. 修改商品信息")
        print("4. 删除商品")
        print("5. 调整库存")
        print("6. 退出系统")

        choice = input("请选择操作（1-6）：")

        if choice == '1':
            add_product()
        elif choice == '2':
            display_products()
        elif choice == '3':
            update_product()
        elif choice == '4':
            delete_product()
        elif choice == '5':
            adjust_stock()
        elif choice == '6':
            print("感谢使用，再见！")
            break
        else:
            print("无效的选项，请重新输入！")


class ProductManager:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("产品管理系统")
        self.window.geometry("800x600")
        
        # 设置整体样式
        style = ttk.Style()
        style.configure("TButton", padding=6, relief="flat", background="#2196F3")
        style.configure("TLabel", padding=5, font=('Arial', 10))
        style.configure("Treeview", rowheight=25)
        
        # 创建主框架
        main_frame = ttk.Frame(self.window, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 左侧输入区域
        input_frame = ttk.LabelFrame(main_frame, text="产品信息", padding="5")
        input_frame.grid(row=0, column=0, padx=5, pady=5, sticky="nsew")
        
        # 输入字段
        ttk.Label(input_frame, text="产品名称:").grid(row=0, column=0, sticky=tk.W)
        self.name_entry = ttk.Entry(input_frame, width=30)
        self.name_entry.grid(row=0, column=1, padx=5, pady=2)
        
        ttk.Label(input_frame, text="价格:").grid(row=1, column=0, sticky=tk.W)
        self.price_entry = ttk.Entry(input_frame, width=30)
        self.price_entry.grid(row=1, column=1, padx=5, pady=2)
        
        # 按钮区域
        button_frame = ttk.Frame(input_frame)
        button_frame.grid(row=2, column=0, columnspan=2, pady=10)
        
        ttk.Button(button_frame, text="添加产品", command=self.add_product).grid(row=0, column=0, padx=5)
        ttk.Button(button_frame, text="更新产品", command=self.update_product).grid(row=0, column=1, padx=5)
        ttk.Button(button_frame, text="删除产品", command=self.delete_product).grid(row=0, column=2, padx=5)
        
        # 右侧产品列表
        list_frame = ttk.LabelFrame(main_frame, text="产品列表", padding="5")
        list_frame.grid(row=0, column=1, padx=5, pady=5, sticky="nsew")
        
        # 创建树形视图
        self.tree = ttk.Treeview(list_frame, columns=("ID", "名称", "价格"), show="headings")
        self.tree.heading("ID", text="ID")
        self.tree.heading("名称", text="名称")
        self.tree.heading("价格", text="价格")
        
        # 设置列宽
        self.tree.column("ID", width=50)
        self.tree.column("名称", width=200)
        self.tree.column("价格", width=100)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        self.tree.grid(row=0, column=0, sticky="nsew")
        scrollbar.grid(row=0, column=1, sticky="ns")
        
        # 配置网格权重
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(0, weight=1)
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)

    def add_product(self):
        try:
            name = self.name_entry.get().strip()
            price = float(self.price_entry.get())
            
            if not name:
                messagebox.showerror("错误", "商品名称不能为空！")
                return
                
            if price < 0:
                messagebox.showerror("错误", "价格不能为负数！")
                return
            
            # 生成唯一ID
            product_id = str(len(products) + 1)
            new_product = Product(product_id, name, price, 0)
            products.append(new_product)
            
            # 更新树形视图
            self.tree.insert('', 'end', values=(product_id, name, f"{price:.2f}"))
            
            # 清空输入框
            self.name_entry.delete(0, tk.END)
            self.price_entry.delete(0, tk.END)
            
            messagebox.showinfo("成功", "商品添加成功！")
            
        except ValueError:
            messagebox.showerror("错误", "请输入有效的价格！")
    
    def update_product(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要修改的商品！")
            return
            
        item = self.tree.item(selected[0])
        product_id = item['values'][0]
        
        product = find_product(str(product_id))
        if product:
            try:
                name = self.name_entry.get().strip()
                price = float(self.price_entry.get())
                
                if name:
                    product.name = name
                if price >= 0:
                    product.price = price
                    
                self.tree.item(selected[0], values=(product_id, name, f"{price:.2f}"))
                messagebox.showinfo("成功", "商品信息已更新！")
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的价格！")
    
    def delete_product(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要删除的商品！")
            return
            
        if messagebox.askyesno("确认", "确定要删除选中的商品吗？"):
            item = self.tree.item(selected[0])
            product_id = item['values'][0]
            
            product = find_product(str(product_id))
            if product:
                products.remove(product)
                self.tree.delete(selected[0])
                messagebox.showinfo("成功", "商品已删除！")
    
    def run(self):
        self.window.mainloop()


if __name__ == "__main__":
    app = ProductManager()
    app.run() 